import { ApimessageInfo } from "../../api/index"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.$path,
    offsetTop: 0,
    contact: {},
    userInfo: {},
    message: "",
    list: [],
    loading: false,
    finish: false,
  },
  endFlag: false, //是否在底部,
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      contact: JSON.parse(options.contact),
      userInfo: await app.getUserInfo()
    })
    this.getMessageList()
    app.ws.onRoom(this.data.contact.patient_id,this.acceptMessage.bind(this))
    app.ws.send({action: 'openPage',uid: this.data.contact.patient_id})
  },

  onShow() {
    app.setWsIsClose(true)
  },

  onHide() {
    
  },


  onReady(){
    this.endDom = this.createIntersectionObserver(
      {
        thresholds: [0],
      }
    ).relativeToViewport().observe("#end",(res) =>{
      this.endFlag = res.intersectionRatio > 0
    })
  },

  acceptMessage(obj) {
    this.data.list.push(obj)
    this.setData({
      list: this.data.list
    },() => {
      wx.vibrateLong({
        // type: "heavy",
        // complete: (res) => {
        //   console.log('res',res)
        // }
      })
      if(this.endFlag){
        wx.pageScrollTo({
          scrollTop: 999999999,
        })
      }
    })
  },

  onPageScroll(e) {
    if(this.data.loading || this.data.finish) return
    if(e.scrollTop === 0) {
      this.getMessageList()
    }
  },

  getMessageList() {
    this.setData({
      loading: true
    })
    const ops = {
      message_id: this.data.list[0]?.id ?? "" ,
      size: 20,
    }
    ApimessageInfo(ops,this.data.contact.patient_id).then(res => {
      const data = res.data || []
      const finish = !data.length
      const list = data.concat(this.data.list)
      const parmas = {
        finish
      }
      if(!finish) {
        parmas.list = list
      }
      this.setData(parmas,() => {
        if(!finish) {
          if(ops.message_id) {
            wx.pageScrollTo({
              selector: `.message_${ops.message_id}`,
              offsetTop: -100,
              duration: 0,
            })
          }else {
            wx.pageScrollTo({
              scrollTop: 999999999,
              duration: 0,
            })
          }
        }
      })
    }).finally(_=>{
      this.setData({
        loading: false
      })
    })
  },

  onHeightchange(e) {
    this.setData({
      offsetTop: e.detail.height
    })
  },

  onInput(e) {
    const value = e.detail.value
    this.setData({
      message: value,
    })
  },

  onConfirm() {
    if(!this.data.message.trim()){
      wx.showToast({
        title: '不能发送空白内容！',
        icon: "none"
      })
      this.setData({
        message: ""
      })
      return
    }
    const contact = this.data.contact
    
    const parmas = {
      action: "message",
      receiver: contact.patient_id,
      content: this.data.message,
      type: "txt",
      sender: this.data.userInfo.id,
      sender_type: "doctor",
      id: Date.now()
    }
    app.ws.send(parmas,() => {
      this.data.list.push(parmas)
      this.setData({
        message: "",
        list: this.data.list
      },() => {
        wx.pageScrollTo({
          scrollTop: 999999999
        })
      })
    },() => {
      wx.showToast({
        title: '发送失败',
        icon: "error"
      })
    })
  },

  openImage(){
    app.setWsIsClose(false)
    wx.chooseMedia({
      count: 3,
      mediaType: ['image'],
      sizeType: ["compressed",'original'],
      success: (res) => {
        const contact = this.data.contact
        const data = res.tempFiles.map((item,index) => {
          return {
            action: "message",
            receiver: contact.patient_id,
            content: "",
            type: "img",
            sender: this.data.userInfo.id,
            sender_type: "doctor",
            id: Date.now() + index,
            file: item.tempFilePath
          }
        })
        const list = this.data.list.concat(data)
        this.setData({
          message: "",
          list: list
        },() => {
          wx.pageScrollTo({
            scrollTop: 999999999
          })
        })
      },
      complete: () =>{
        app.setWsIsClose(true)
      }
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    app.ws.send({action: 'openPage',uid: this.data.contact.patient_id})
    app.ws.removeRoom(this.data.contact.patient_id)
    this.endDom && this.endDom.disconnect()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage() {

  // }
})